$(document).ready(function () {
    Modernizr.load();

    $('.validate-form').validate({ ignore: ''});

    $('.share-link').click(function () {
        $(this).focus();
        $(this).select();
    });

    //qtip tooltip
    $('.tip').qtip({
        content: {
            attr: 'title'
        },
        position: {
            my: 'bottom center',  // Position my top left...
            at: 'top center', // at the bottom right of...
            target: $('.tip') // my target
        },
        style: {
            classes: 'ui-tooltip-default ui-tooltip-tipped',
            tip: {
                height: 4
            }
        }
    });

    //latest tweet
    $.getJSON("https://api.twitter.com/1/users/show.json?screen_name=roccacreative&callback=?", function (data) {
        $(".tweet p").html(data.status.text);
    });

    $(".upload-web").click(function () {
        if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
            alert('Web upload isn\'t avaliable in outdated browsers, please upgrade your browser.');
        } else {

            $('#container').qtip({
                content: {
                    text: $('.upload-web-box').parent().html()
                },
                solo: true,
                position: {
                    my: 'center', // ...at the center of the viewport
                    at: 'center',
                    target: $(window)
                },
                show: {
                    event: false, // Disable any show events
                    ready: true, // Show it straight away
                    delay: 0, // Remove default 90ms delay
                    modal: true,
                    target: $(window)
                },
                hide: false,
                style: {
                    classes: 'loading-box ui-tooltip-light'
                },
                events: {
                    render: function (event, api) {
                        $('.ui-tooltip .box').parentsUntil().removeClass('ui-tooltip-default');
                    },
                    show: function (event, api) {
                        api.elements.content.find('.cancel-upload').click(function () {
                            $('#container').qtip('hide');
                        });
                    }
                }
            });
        }
    }); //

    $(".send-email").click(function () {

        $.blockUI({
            message: $('.send-email-box'), css: { width: '430px' }, onBlock: function () {                
                $('.blockOverlay').attr('title', 'Click to unblock').click($.unblockUI);                
            }
        });
        $(".blockUI.blockMsg").center();
    });  //send email

    $(".logo").click(function () {

        $('#container').qtip({
            content: {
                text: $('.uploading-box').parent().html()
            },
            solo: true,
            position: {
                my: 'center', // Use the corner...
                at: 'center' // ...and opposite corner
            },
            hide: false, // Disable hide events
            show: {
                event: false, // Disable any show events
                ready: true, // Show it straight away
                delay: 0, // Remove default 90ms delay
                modal: {
                    on: true,
                    blur: false,
                    delay: 0
                }
            },
            style: {
                classes: 'loading-box ui-tooltip-light'
            },
            events: {
                render: function (event, api) {
                    $('.box').parentsUntil().removeClass('ui-tooltip-default');

                },
                show: function (event, api) {
                    api.elements.content.find('.cancel-upload').click(function () {
                        $('#container').qtip('hide');
                    });
                }
            }
        });
    });

    //index upload 
    $('.form-uploadweb').live('submit', function () {
        $(this).attr('disabled', 'disabled');
        var url = $('.web-url')[1].value;
        if (url.length > 0) {

            // if user has not entered a schema, assume http
            if (!/^(https?|ftp):\/\//i.test(url)) {
                url = 'http://' + url;
                $('.web-url:first-child').val(url);
            }

            if (validateURL($('.web-url')[1], url)) {
                $('.web-url').removeClass('error');
                $('.cancel-upload').trigger('click');
                $.post('/File/UploadWeb', { url: $('.web-url')[1].value }, function (data) {
                    if (!data.success) {
                        $('.upload-options').prevUntil('.msg').removeClass('msg-good').addClass('msg-bad');
                        $('.msg-bad').html(data.message);
                        console.log(data.message);
                    }
                    else {
                        $('.upload-options').prevUntil('.msg').removeClass('msg-bad');
                        $('.upload-options').prevUntil('.msg').addClass('msg-good');
                        $('.upload-options').after($('.uploadweb-progress-wrap').parent().html());
                        updateProgress(data.uploadId);
                    }
                });

            } else {
                $('.web-url').addClass('error');
            }

        } else {
            $('.web-url').addClass('error');

        }
        return false;
    });

    var slugs = new Array();
    var hashes = new Array();

    //uploadify
    $('#upload-computer').uploadify({
        'swf': '/content/flash/uploadify.swf',
        'uploader': '/file/upload',
        'height': '57px',
        'width': '150px',
        'buttonText': 'Computer',
        'multi': true,
        'fileSizeLimit': '2GB',
        'onUploadSuccess': function (file, data, response) {
            var fileInfo = JSON.parse(data);
            if (fileInfo.success) {
                slugs.push(fileInfo.slug);
                hashes.push(fileInfo.hash);
            }
            else {
                $.blockUI({
                    message: fileInfo.message, css: { width: '250px', padding: '20px' }, onBlock: function () {
                        $('.blockOverlay').attr('title', 'Click to unblock').click($.unblockUI);
                    }
                });
                $(".blockUI.blockMsg").center();
            }
        },
        'onQueueComplete': function (queueData) {
            if (slugs.length == 1) {
                window.location = '/complete/' + slugs[0] + '/' + hashes[0];
            }
            else if (slugs.length > 1) {
                $('.qSlugs').val(JSON.stringify(slugs));
                $('.qHashes').val(JSON.stringify(hashes));

                $.blockUI({
                    message: $('.multiple-files-box'), css: { width: '420px', padding: '20px' }, onBlock: function () {
                    }
                });
                $(".blockUI.blockMsg").center();
            }
            else {

            }
        }
        // Put your options here
    });
}); ////doc

function updateProgress(uploadId) {
    var progressInterval = setInterval(function () {
        $.post('/File/UploadWebProgress', { uploadId: uploadId }, function (data) {
            var progress = data.progress;
            var recieved = data.recieved;
            var total = data.total;
            var slug = data.slug;
            var hash = data.hash;

            var w = progress;
            var prog_width = Math.ceil(w) * 3;


            $('.web-uploadify .uploadify-progress-bar').animate({ width: prog_width + 'px' }, 300);
            $('.web-uploadify .data').text(' - ' + progress + '%');


            console.log(progress);
            if (progress == 100) {

            }

            if (slug) {
                clearInterval(progressInterval);
                window.location = '/complete/' + slug + "/" + hash;
            }
        });
    }, 300);
}

function validateURL(element, url) {

    var badTypes = new Array("conf", "txt", "bat", "exe");
    var urlend = url.substring(url.lastIndexOf('/') + 1);
    if (urlend.length > 0) {
        if (/([^\\]+)$/.exec(urlend)[1] && url.length) {
            var filename = /([^\\]+)$/.exec(urlend)[1];

            if (filename.indexOf(".") >= 0) {

                var ext = filename.substr(filename.lastIndexOf('.') + 1);

                if (jQuery.inArray(ext, badTypes) > 0) {
                    return false;
                } else {
                    var urlregex = new RegExp(
                          "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]?");

                    return urlregex.test(url);
                }

            } else {
                return false;
            }

        } else { return false; }
    } else { return false; }

} //validate url

(function ($) {
    $.fn.center = function () {
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
        this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
        return this;
    };
})(jQuery);

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
};